package com.twan.kotlinbase.util

import android.content.Context
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.XPopupImageLoader
import com.twan.kotlinbase.R
import java.io.File

//使用xpoup的图片预览,详情 #{ImageViewerDemo.kt}
object XpopupUtils {

    //预览单张图
    fun previewSingleImage(context: Context, imgView: ImageView, filepath: String){
        XPopup.Builder(context).asImageViewer(imgView, filepath, ImageLoader()).show()
    }


    //预览多图
    /**
     * position adapter的position
     * imgView rv的item的ImageView
     * datas 图片结合
     */
    fun previewMultiImgs(context: Context,position:Int, imgView: ImageView,datas:MutableList<Any>){
        XPopup.Builder(context).asImageViewer(imgView, position, datas, { popupView, position ->
            val rv = imgView.parent as RecyclerView
            popupView.updateSrcView(rv.getChildAt(position) as ImageView)
        }, ImageLoader()).show()
    }



    class ImageLoader : XPopupImageLoader {
        override fun loadImage(position: Int, url: Any, imageView: ImageView) {
            //必须指定Target.SIZE_ORIGINAL，否则无法拿到原图，就无法享用天衣无缝的动画
            Glide.with(imageView).load(url).apply(RequestOptions().placeholder(R.mipmap.test).override(Target.SIZE_ORIGINAL)).into(imageView)
        }

        override fun getImageFile(context: Context, uri: Any): File? {
            try {
                return Glide.with(context).downloadOnly().load(uri).submit().get()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return null
        }
    }
}